﻿using System;
using System.Web;
using ActivityFeed.Web.RavenDB;
using OpenWaves.ActivityFeed.RavenDB;

namespace OpenWaves.ActivityFeed.Web.RavenDB
{
    public class DocumentSessionPerRequestHttpModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += this.OnContextOnBeginRequest;
            context.EndRequest += this.OnContextOnEndRequest;
        }

        private void OnContextOnBeginRequest(object sender, EventArgs args)
        {
            DocumentSessionPerRequestProvider.CurrentDocumentSession = ActivityFeedDocumentStore.Current.OpenSession();
        }

        private void OnContextOnEndRequest(object sender, EventArgs args)
        {
            if (DocumentSessionPerRequestProvider.CurrentDocumentSession == null)
                return;

            if (HttpContext.Current.Error == null)
                DocumentSessionPerRequestProvider.CurrentDocumentSession.SaveChanges();

            DocumentSessionPerRequestProvider.CurrentDocumentSession.Dispose();
            DocumentSessionPerRequestProvider.CurrentDocumentSession = null;
        }

        public void Dispose()
        {
        }
    }
}